﻿using System;
using System.Net;
using System.Threading;
using System.Windows;

namespace Wp7Tools.Services {
    public class WebClientService : IWebClientService {
        public void DownloadAsync(Uri uri, Action<string> actionOk, Action<Exception> actionError) {
			WebClientRequest request = new WebClientRequest {
				Uri = uri, 
				ActionOk = actionOk, 
				ActionError = actionError
			};

        	if(IsThreadUI()) {
				GetOutThreadUI(request);
				return;
			}
        	GoDownloadString(request);
        }

    	private bool IsThreadUI() {
    		return Deployment.Current.Dispatcher.CheckAccess();
    	}

    	private void GetOutThreadUI(WebClientRequest request) {
    		ThreadPool.QueueUserWorkItem(GoDownloadString, request);
    	}

    	private void GoDownloadString(object state) {
    		WebClientRequest request = (WebClientRequest) state;

			WebClient client = new WebClient();
			client.DownloadStringCompleted += (s, e) => {
				if (e.Error != null) {
					request.ActionError.Invoke(e.Error);
					return;
				}
				request.ActionOk.Invoke(e.Result);
			};
			client.DownloadStringAsync(request.Uri);
    	}
    }
}